package com.mrcode.neptuneproject.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.mrcode.neptuneproject.common.Result;
import com.mrcode.neptuneproject.domain.req.ErnieBotSingleWheelReq;
import com.mrcode.neptuneproject.domain.req.Messages;
import com.mrcode.neptuneproject.domain.resp.AccessTokenResp;
import com.mrcode.neptuneproject.domain.resp.ErnieBotSingleWheelResp;
import com.mrcode.neptuneproject.service.ErnieBotService;
import com.mrcode.neptuneproject.util.MyHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author YSH hz22057727
 * @Date 2023/11/17 11:00
 * @Version 1.0
 */
@Slf4j
@Service
public class ErnieBotServiceImpl implements ErnieBotService {

    @Value("${ernieBot.address}")
    private String address;
    @Value("${ernieBot.apiKey}")
    private String apiKey;
    @Value("${ernieBot.secretKey}")
    private String secretKey;
    @Value("${ernieBot.accessTokenAddress}")
    private String accessTokenAddress;

    private static String ACCESS_TOKEN = "";
    private final static String AUTHENTICATION_ERROR = "110";

    @Override
    public Result<String> getErnieBotAnswer(String prompt) {
        //如果没有access_token，获取access_token
        if (!StringUtils.hasText(ACCESS_TOKEN)) {
            this.getAccessToken();
        }
        ErnieBotSingleWheelReq requestInfo = new ErnieBotSingleWheelReq();
        List<Messages> messages = new ArrayList<>();
        Messages messagesInfo = new Messages();
        messagesInfo.setRole("user");
        messagesInfo.setContent(prompt);
        messages.add(messagesInfo);
        requestInfo.setMessages(messages);
        //构建请求
        String requestUrl = address + "?access_token=" + ACCESS_TOKEN;
        String postResult = MyHttpUtils.doPost(requestUrl, JSONObject.toJSONString(requestInfo));
        if (!StringUtils.hasText(postResult)) {
            return Result.error("调用ErnieBot API！返回数据为空！");
        }
        ErnieBotSingleWheelResp resp = JSONObject.parseObject(postResult, ErnieBotSingleWheelResp.class);
        if (StringUtils.hasText(resp.getErrorCode())) {
            return Result.error("调用ErnieBot API出错！ERROR IS：" + resp.getErrorCode() + "," + resp.getErrorMsg());
        }
        //token失效情况
        if (AUTHENTICATION_ERROR.equals(resp.getErrorCode())) {
            this.getAccessToken();
            return Result.error("调用ErnieBot token失效，已刷新token请重新发起请求！");
        }
        return Result.success(resp.getResult());
    }

    @Override
    public void getAccessToken() {
        //构建请求
        String requestUrl = accessTokenAddress + "?grant_type=client_credentials" + "&client_id=" + apiKey + "&client_secret=" + secretKey;
        String responseBody = MyHttpUtils.doPost(requestUrl, "none");
        if (!StringUtils.hasText(responseBody)) {
            throw new RuntimeException("调用Ernie API：获取access_token出错！返回数据为空！");
        }
        AccessTokenResp tokenResp = JSONObject.parseObject(responseBody, AccessTokenResp.class);
        if (StringUtils.hasText(tokenResp.getError())) {
            throw new RuntimeException("调用Ernie API：获取access_token出错！ERROR IS：" + tokenResp.getError() + "," + tokenResp.getErrorDescription());
        }
        ACCESS_TOKEN = tokenResp.getAccessToken();
    }
}
